package com.atomscat.lottery.service;

import com.atomscat.lottery.entity.vo.request.GreetUserRequest;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.bean.WxOAuth2UserInfo;
import me.chanjar.weixin.common.bean.oauth2.WxOAuth2AccessToken;
import me.chanjar.weixin.mp.api.WxMpMessageRouter;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.bean.kefu.WxMpKefuMessage;
import me.chanjar.weixin.mp.bean.message.WxMpXmlMessage;
import me.chanjar.weixin.mp.bean.message.WxMpXmlOutMessage;
import org.springframework.jms.annotation.JmsListener;
import org.springframework.jms.core.JmsTemplate;
import org.springframework.stereotype.Service;

@Slf4j
@Service
@RequiredArgsConstructor
public class ReceiveWeChatService {

    private final WxMpService wxService;
    private final JmsTemplate jmsTemplate;
    private final WxMpMessageRouter messageRouter;
    private final ParticipateActivityService participateActivityService;

    public String receiveWeChat(String appid, String requestBody, String signature, String timestamp, String nonce, String openid, String encType, String msgSignature) {
        String out = null;
        if (encType == null) {
            // 明文传输的消息
            WxMpXmlMessage inMessage = WxMpXmlMessage.fromXml(requestBody);
            WxMpXmlOutMessage outMessage = this.route(inMessage);
            if (outMessage == null) {
                return "";
            }
            out = outMessage.toXml();
        } else if ("aes".equalsIgnoreCase(encType)) {
            // aes加密的消息
            WxMpXmlMessage inMessage = WxMpXmlMessage.fromEncryptedXml(requestBody, wxService.getWxMpConfigStorage(), timestamp, nonce, msgSignature);
            log.debug("\n消息解密后内容为：\n{} ", inMessage.toString());
            WxMpXmlOutMessage outMessage = this.route(inMessage);
            if (outMessage == null) {
                return "";
            }
            out = outMessage.toEncryptedXml(wxService.getWxMpConfigStorage());
        }

        log.debug("\n组装回复信息：{}", out);
        return out;
    }

    private WxMpXmlOutMessage route(WxMpXmlMessage message) {
        try {
            return this.messageRouter.route(message);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            throw new RuntimeException(e.getMessage());
        }
    }

    /**
     * 接收微信请求，转发到消息队列
     *
     * @param appid       微信公众号appid
     * @param requestBody 请求体
     * @param signature   签名
     * @param timestamp   时间戳
     * @param nonce       随机数
     * @param openid      用户openid
     * @param encType     加密类型
     * @param msgSignature 消息签名
     * @return 响应消息
     */
    public String receiveWeChatToMq(String appid, String requestBody, String signature, String timestamp, String nonce, String openid, String encType, String msgSignature) {
        if (encType == null) {
            // 明文传输的消息
            WxMpXmlMessage inMessage = WxMpXmlMessage.fromXml(requestBody);
            jmsTemplate.convertAndSend("wx-receive-topic", inMessage);
        } else if ("aes".equalsIgnoreCase(encType)) {
            // aes加密的消息
            WxMpXmlMessage inMessage = WxMpXmlMessage.fromEncryptedXml(requestBody, wxService.getWxMpConfigStorage(), timestamp, nonce, msgSignature);
            jmsTemplate.convertAndSend("wx-receive-topic", inMessage);
        }
        return "";
    }

    @JmsListener(destination = "DLQ")
    public void handleDLQ(Object deadMessage) {
        if (deadMessage instanceof WxMpXmlMessage) {
            this.route((WxMpXmlMessage) deadMessage);
        } else if (deadMessage instanceof GreetUserRequest) {
            greetUser((GreetUserRequest) deadMessage);
        }
    }

    @JmsListener(destination = "wx-receive-topic")
    public void receiveMessage(WxMpXmlMessage inMessage) {
        this.route(inMessage);
    }

    public void greetUserToMq(String appid, Long lotteryActivityId, String code) {
        GreetUserRequest request = new GreetUserRequest();
        request.setAppid(appid);
        request.setLotteryActivityId(lotteryActivityId);
        request.setCode(code);
        jmsTemplate.convertAndSend("greet-user-topic", request);
    }

    @JmsListener(destination = "greet-user-topic")
    public void greetUserMessage(GreetUserRequest request) {
        greetUser(request);
    }

    public void greetUser(GreetUserRequest request) {
        String msg = "参与活动失败，请重新点击链接参与活动";
        String openId = null;
        try {
            WxOAuth2AccessToken accessToken = wxService.getOAuth2Service().getAccessToken(request.getCode());
            WxOAuth2UserInfo user = wxService.getOAuth2Service().getUserInfo(accessToken, null);
            openId = user.getOpenid();
            participateActivityService.participate(user, request.getLotteryActivityId(), request.getAppid());
            msg = "您已经成功参与活动，请耐心等待开奖";
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            msg = e.getMessage();
        }
        try {
            wxService.getKefuService().sendKefuMessage(WxMpKefuMessage.TEXT().toUser(openId).content(msg).build());
        } catch (Exception e) {
            log.error("", e);
        }
    }

}
